/*
 * @Author: 郑灶欣
 * @Date: 2023-02-06 14:22:41
 * @LastEditors: 郑灶欣
 * @LastEditTime: 2023-02-06 14:36:33
 * @FilePath: \office\src\api\utils\request.ts
 * @Description: 
 */
import axios from 'axios';
import { errorCodeType } from './error-code-type';

// 创建axios实例
const service = axios.create({
    // 服务接口请求
    baseURL: import.meta.env.VITE_APP_BASE_API,
    // 超时设置
    timeout: 15000,
    headers:{'Content-Type':'application/json;charset=utf-8'}
})



// 请求拦截
service.interceptors.request.use(config => {
    // 是否需要设置 token
    // config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    // get请求映射params参数
    return config
}, error => {
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((res:any) => {
        // 未设置状态码则默认成功状态
        const code = res.data['code'] || 200;
        // 获取错误信息
        const msg = errorCodeType(code) || res.data['msg'] || errorCodeType('default')
        if(code === 200){
            return Promise.resolve(res.data)
        }else{
            return Promise.reject(res.data)
        }
    },
    //请求错误
    error => {
        console.log('err' + error)
        let { message } = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        }
        else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        }
        else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        return Promise.reject(error)
    }
)

export default service;